package hdaccp.liteamall.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@PropertySource("classpath:jdbc.properties")
public class MyBatisConfig {
    @Value("${driver}")
    private String driver ;
    @Value("${url}")
    private String url ;
    @Value("${uname}")
    private String username ;
    @Value("${password}")
    private String password ;
    @Bean
    public DataSource getDataSource(){
        DruidDataSource ds = new DruidDataSource() ;
        ds.setPassword(password);
        ds.setUsername(username);
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        return ds ;
    }

    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean() ;
        //1.设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        //2.设置mybatis-config.xml
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver() ;
        sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
        //3.mapper/*.xml
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.包中类的别名
        sqlSessionFactoryBean.setTypeAliasesPackage("hdaccp.liteamall.entity");
        return sqlSessionFactoryBean ;
    }

    @Configuration
    @AutoConfigureAfter(SqlSessionFactoryBean.class)
    public static class ScanMapper{
        @Bean
        public MapperScannerConfigurer getMapperScannerConfigurer(){
            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer() ;
            mapperScannerConfigurer.setBasePackage("hdaccp.liteamall.dao");
            return mapperScannerConfigurer ;
        }
    }
}
